/*
 * @Author: HuiWen Gong huiwings@163.com
 * @Date: 2022-11-07 15:48:51
 * @LastEditors: HuiWen Gong huiwings@163.com
 * @LastEditTime: 2023-12-14 17:01:39
 * @FilePath: \flutter_levin\lib\ui\pages\main\main_tab.dart
 * @Description: 
 * 
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved. 
 */
import 'package:flutter/material.dart';
import 'package:flutter_levin/config/app_manager.dart';
import 'package:flutter_levin/ui/pages/main/home_page.dart';
import 'package:flutter_levin/ui/pages/main/knowledge_page.dart';
import 'package:flutter_levin/ui/pages/main/mine_page.dart';
import 'package:flutter_levin/ui/pages/main/store_page.dart';
import 'package:flutter_levin/ui/weight/dialog_notify.dart';
import 'package:logger/logger.dart';

class MainTabPage extends StatefulWidget {
  const MainTabPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MainTabState();
  }
}

class _MainTabState extends State<MainTabPage> {
  final _pageController = PageController();
  int _currentIndex = 0;
  int _lastExitAt = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        onWillPop: _exit,
        child: PageView.builder(
          itemBuilder: (ctx, index) => pages[index],
          itemCount: pages.length,
          controller: _pageController,
          physics: const NeverScrollableScrollPhysics(),
          onPageChanged: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: Theme.of(context).primaryColor,
        selectedItemColor: Theme.of(context).colorScheme.onPrimary,
        unselectedItemColor: Theme.of(context).colorScheme.tertiary,
        selectedFontSize: 14,
        unselectedFontSize: 14,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '资讯'),
          BottomNavigationBarItem(
              icon: Icon(Icons.lightbulb_outline), label: '知识'),
          BottomNavigationBarItem(icon: Icon(Icons.list), label: '书架'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
        currentIndex: _currentIndex,
        onTap: (index) {
          _pageController.jumpToPage(index);
        },
      ),
    );
  }

  Future<bool> _exit() {
    int currentAt = DateTime.now().millisecondsSinceEpoch;
    if (currentAt - _lastExitAt > 1500) {
      showToast('退出APP');
      _lastExitAt = currentAt;
    } else {
      AppManager.pop();
    }
    return Future.value(false);
  }

  List<Widget> pages = <Widget>[
    const HomePage(),
    const KnowledgePage(),
    const StorePage(),
    const MinePage()
  ];
}
